#pragma once
#include <vector>

namespace sjh
{
	template <class T>
	struct less
	{
		bool operator()(const T& x, const T& y)
		{
			return x < y;
		}
	};

	template <class T>
	struct greater
	{
		bool operator()(const T& x, const T& y)
		{
			return x > y;
		}
	};

	template <class T,class Container=vector<T>,class compare=less<T>>
	class priority_queue
	{
		void adjust_up(int child)
		{
			size_t parent = (child - 1) / 2;

			while (child > 0)
			{
				//if (_con[child] > _con[parent])
				if (compare()(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);
					child = parent;
					parent = (parent - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}

		void adjust_down(int parent)
		{
			size_t child = parent * 2 + 1;
			//if (child + 1 < _con.size() && _con[child + 1] > _con[child])
			if (child + 1 < _con.size() 
				&& compare()(_con[child], _con[child + 1]))
			{
				child += 1;
			}

			while (child < _con.size())
			{
				if (compare()(_con[parent], _con[child]))
				{
					swap(_con[child], _con[parent]);
					parent = child;
					child = child * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}
	public:
		void push(const T& x)
		{
			_con.push_back(x);
			adjust_up(_con.size() - 1);
		}
		void pop()
		{
			swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();
			adjust_down(0);
		}
		const T& top()
		{
			return _con[0];
		}

		size_t size()
		{
			return _con.size();
		}
		
		bool empty()
		{
			return _con.empty();
		}
	private:
		Container _con;
	};

	void test()
	{
		priority_queue<int> q1;
		q1.push(34);
		q1.push(26);
		q1.push(98);
		q1.push(67);
		q1.push(65);
		q1.push(45);

		while (!q1.empty())
		{
			cout << q1.top() << " ";
			q1.pop();
		}
		cout << endl;
		priority_queue<int, vector<int>, greater<int>> q2;
		q2.push(34);
		q2.push(26);
		q2.push(98);
		q2.push(67);
		q2.push(65);
		q2.push(45);

		while (!q2.empty())
		{
			cout << q2.top() << " ";
			q2.pop();
		}
	}
}